<template>
	<view class="min-h-screen bg-gray-100">
		<view class="px-3 py-2 cartList">
			<view v-for="item in cartList" :key="item._id" class="bg-white rounded-lg mb-2 p-3">
				<view class="flex items-center">
					<wd-checkbox v-model="item.selected" @change="
                            val => {
                                handleSelectChange(val, item._id);
                            }
                        " />
					<image :src="item.cover" class="w-102px h-102px ml-2 rounded" mode="aspectFill" />
					<view class="flex-1 ml-2">
						<view class="text-sm line-clamp-2">{{ item.skuName }}</view>
						<view class="text-red-500 font-bold mt-1">￥{{ item.price }}</view>
						<view class="flex justify-between items-center mt-2">
							<wd-input-number v-model="item.quantity" :min="1" :max="item.sku.stock" size="small"
								@change="
                                    val => {
                                        handleQuantityChange(val, item._id);
                                    }
                                " />
							<wd-button type="danger" size="small" @click="handleDelete(item)">删除</wd-button>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="fixed bottom-0 left-0 right-0 bg-white px-4 py-2 flex items-center justify-between">
			<view class="flex items-center">
				<wd-checkbox v-model="isAllSelected">全选</wd-checkbox>
			</view>
			<view class="flex items-center">
				<view class="mr-4">
					<view class="text-sm text-gray-500">合计</view>
					<view class="text-red-500 font-bold">￥{{ totalPrice }}</view>
				</view>
				<wd-button type="primary" :disabled="!hasSelectedItems"
					@click="handleCheckout">结算({{ selectedCount }})</wd-button>
			</view>
		</view>
	</view>
	<wd-message-box />
</template>

<script setup>
	import {
		getCartList,
		updateCart,
		deleteCart,
		selectAllCart
	} from "@/api/shoppingCart";
	import {
		ref,
		computed
	} from "vue";
	import {
		useToast,
		useMessage
	} from "wot-design-uni";

	const toast = useToast();
	const message = useMessage();

	const cartList = ref([]);

	const fetchCartList = async () => {
		const res = await getCartList();
		cartList.value = res.data;
	};

	fetchCartList();

	const isAllSelected = computed({
		get: () => {
			return cartList.value.length && cartList.value.every(item => item.selected === true);
		},
		set: async val => {
			if (val) {
				cartList.value.forEach(item => {
					item.selected = true;
				});
				uni.showLoading({
					duration: 0
				});
				await selectAllCart(true);
			} else {
				cartList.value.forEach(item => {
					item.selected = false;
				});
				uni.showLoading({
					duration: 0
				});
				await selectAllCart(false);
			}
			await fetchCartList();
			uni.hideLoading();
		},
	});

	const totalPrice = computed(() => {
		return cartList.value
			.filter(item => item.selected)
			.reduce((totalPrice, item) => totalPrice + item.price * item.quantity, 0)
			.toFixed(2);
	});

	const selectedCount = computed(() => {
		return cartList.value.filter(item => item.selected).length;
	});

	const hasSelectedItems = computed(() => {
		return selectedCount.value > 0;
	});

	const handleSelectChange = async (val, _id) => {
		uni.showLoading({
			duration: 0
		});
		await updateCart({
			_id,
			selected: val.value,
		});
		await fetchCartList();
		uni.hideLoading();
	};

	const handleQuantityChange = async (val, _id) => {
		console.log("数量变化:", val);
		uni.showLoading({
			duration: 0
		});
		await updateCart({
			_id,
			quantity: val.value,
		});
		await fetchCartList();
		uni.hideLoading();
	};

	const handleDelete = async item => {
		await message.confirm("确定要删除这个商品吗？");
		uni.showLoading({
			duration: 0
		});
		await deleteCart(item._id);
		await fetchCartList();
		uni.hideLoading();
	};
	
	const handleCheckout = () => {
		const selectedItems = cartList.value.filter(item => item.selected);
		if (selectedItems.length === 0) {
			toast.warning("请选择要结算的商品");
			return;
		}
		uni.navigateTo({
			url: "/pages/confirm/confirm",
		});
	};
</script>

<style>
	.line-clamp-2 {
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	.cartList {
		height: calc(100vh - 67px);
		overflow: scroll;
	}
</style>